<?php
/**
 * Description: 根据归类获取知识点讲解内容
 * User: devforma
 * Date: 15/1/13
 * Time: 21:37
 */

class GetGuileiDetail implements iController {

    /**
     * api请求处理主函数
     * 
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {

        global $cmsdb;

        //为了兼容老版本app,每个归类增加id关联(参照GetTaskDetail)
        $tempGuilei = [
            '1' => '考点',
            '2' => '技巧',
            '3' => '拓展'
        ];

        if (empty($queryArgs['guilei_id']) || !filter_var($queryArgs['guilei_id'], FILTER_VALIDATE_INT)
            || empty($queryArgs['note_id']) || !filter_var($queryArgs['note_id'], FILTER_VALIDATE_INT)) {
            return genOutput(1000);
        }

        $sql = 'SELECT * FROM `wp_posts` AS p INNER JOIN `relation_topic_note` AS n ON p.ID=n.topic_id AND n.note_id=:note_id 
        WHERE p.post_mime_type=:guilei AND p.post_type="page" AND p.post_status="publish" AND p.post_parent=0 ORDER BY p.ID';
        $parentArray = $cmsdb->getResults($sql, [':note_id' => $queryArgs['note_id'], ':guilei' => $tempGuilei[$queryArgs['guilei_id']]]);

        if (empty($parentArray))
            return genOutput(1000);

        //获取子文章
        $parentIds = array();
        foreach ($parentArray as $row) {
            $parentIds[] = $row->ID;
        }

        $parent = array();
        $parentIdsStr = implode(',', $parentIds);
        $sql = "SELECT * FROM `{$cmsdb->posts}` WHERE `post_parent` IN ($parentIdsStr) AND `post_status`='publish'";
        $childPosts = $cmsdb->getResults($sql);
        if (empty($childPosts)) 
            return genOutput(1000);

        foreach ($childPosts as $child) {
            if (!isset($parent["$child->post_parent"])) {
                //初始化母文章对应的内容
                $parent["$child->post_parent"] = array(
                    'id' => 0,
                    'name' => '',
                    'images' => array(),
                    'sections' => array()
                );
            }

            //title处理
            $title = strtok($child->post_title, ' -');
            if ($title == "考点定位") continue;
            if (strpos($title, "真题自测") !== false)
                $title = str_replace("真题自测", "例题", $title);
            if (strpos($title, "真题解析") !== false)
                $title = str_replace("真题解析", "例题解析", $title);
            if (strpos($title, "概述") !== false)
                $title = "";
            if (strpos($title, "详解") !== false)
                $title = "详解";

            //内容处理
            $content = trim(htmlspecialchars_decode($child->post_content));
            $parent["$child->post_parent"]["sections"][] = array(
                'title' => $title,
                'content' => self::getImageItem($parent["$child->post_parent"]['images'], $title, $content) //处理该内容块的图片
            );
        }

        //填充母文章字段
        foreach ($parentArray as $row) {
            $parent["$row->ID"]['id'] = intval($row->ID);
            $parent["$row->ID"]['name'] = trim(strtok($row->post_title, '-'));
        }

        return genOutput(1, array('content' => array_values($parent)));
    }
	
    /**
     * 知识点中分离图片
     * @param array $images 存放图片的数组
     * @param string $title 图片出现内容块的title
     * @param string $content 图片所在内容块的内容
     * @return string 去掉图片标记的内容
     */
    private static function getimageItem(&$images, $title, $content) {
        //$content = preg_replace('/\s+/', "", $content);
        $match = explode("#", $content);
        if(!empty($match)){
            $pos = "front";
            foreach($match as $block){
                if(!empty($block)){
                    if(strpos($block, "jpg") !== false || strpos($block, 'png') !== false){
                        preg_match('_(\d+x\d+)_', $block, $size);
                        $size[0] = empty($size[0]) ? "" : $size[0];
                        $images[] = array(
                            "filename" => FILE_BASE_URL . $block,
                            "title" => $title,
                            "position" => $pos,
                            "size" => $size[0]
                        );

                    }else{
                        $pos = "end";
                    }
                }
            }
        }
		
        return preg_replace("/#[^#]+#/", "", $content);
    }
}
